package datastructure;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-11-20 下午3:28
 */
public class Chapter6_2 {
    public static void main(String[] args) {
        MyBitmap bitmap = new MyBitmap(128);
        bitmap.setBit(126);
        bitmap.setBit(78);
        System.out.println(bitmap.getBit(126));
        System.out.println(bitmap.getBit(78));
    }

    private static class MyBitmap {
        //每一个word是一个long类型元素，对应一个64位二进制数据
        private long[] words;
        //Bitmap的位数大小
        private int size;

        public MyBitmap(int size) {
            this.size = size;
            this.words = new long[(getWordIndex(size - 1) + 1)];
        }

        /**
         * 判断Bitmap某一位的状态
         *
         * @param bitIndex
         * @return
         */
        public boolean getBit(int bitIndex) {
            if (bitIndex < 0 || bitIndex > size - 1) {
                throw new IndexOutOfBoundsException("超过了bitmap有效范围");
            }
            int wordIndex = getWordIndex(bitIndex);
            return (words[wordIndex] & (1L << bitIndex)) != 0;
        }

        /**
         * 把bitmap某一位设置为true
         *
         * @param bitIndex
         */
        public void setBit(int bitIndex) {
            if (bitIndex < 0 || bitIndex > size - 1) {
                throw new IndexOutOfBoundsException("超过了bitmap有效范围");
            }
            int wordIndex = getWordIndex(bitIndex);
            words[wordIndex] |= (1L << bitIndex);
            printBit(words);
        }

        /**
         * 定位bitmap某一位所对应的word
         *
         * @param bitIndex
         * @return
         */
        private int getWordIndex(int bitIndex) {
            //右移６位，相当于除以64
            return bitIndex >> 6;
        }

        private void printBit(long[] array) {
            for (int i = 0; i < array.length; i++) {
                System.out.println(Long.toBinaryString(array[i]));
            }
        }
    }
}
